<?php
class UserController extends Zendk_Controller_Action{

	
	public function indexAction(){

	}
	
	public function preDispatch(){
		
	}

	public function registerAction(){
		$province=new Default_Model_Province();
		$this->view->listProvinces=$province->fetchAll()->toArray();		
		if($this->_request->isPost()){
			$params=$this->_request->getParams();
			$util=new Zendk_Utils();
            if(!isset($params['checkterms'])){$this->view->notice="Bạn phải đồng ý với các điều khoản trên!";return;}
			if(strlen(trim($params['txtName']," "))){
			 if(strlen(trim($params['selGender']," "))){
				if($util->validateEmail($params['txtEmail'],$params['txtReEmail'])){
					if($util->validatePasswords($params['txtPassword'],$params['txtRepassword'])){
					   if($util->mobileVnCheck($params['txtPhone'])){
					       if(strlen(trim($params['selDistrict']," "))){
					           if(strlen(trim($params['txtAddress']," "))){
        						$member=new Default_Model_Member();
        						//echo md5($params['email']);die();
        						$member->insert(array(
        							'Name'		    =>		$params['txtName'],
                                    'Gender'		=>		$params['selGender'],
        							'Email'			=>		$params['txtEmail'],
        							'Phone'			=>		$params['txtPhone'],
        							'DistrictId'	=>		$params['selDistrict'],
        							'Address'		=>		$params['txtAddress'],
                                    'CompanyName'   =>      $params['txtCompany'],
                                    'TaxCode'       =>      $params['txtTaxCode'],
        							'Password'		=>		md5($params['txtPassword']),
        							'ActiveKey'		=>		md5($params['txtEmail'])
        						));	    
                                $this->_redirect('/user/login');                  
    					       }else{
    					           $this->view->notice1="Bạn chưa điền địa chỉ chi tiết rồi!";
    					       }
                           }else{
    					        $this->view->notice2="Bạn chưa chọn Quận/Huyện!";
    					   }
                        }else{
    					   $this->view->notice3="phone number is incorrect!";
    					}
                    }else{
					   $this->view->notice4="password is incorrect!";
				    }
				}else{
				    $this->view->notice5="email is incorrect!";
                }
			 }else{
			     $this->view->notice6="Bạn chưa chọn giới tính!";
			 }
            }else{
			     $this->view->notice7="Bạn chưa điền tên rồi!";
			}
        }
    }
            
	
	public function loadDistrictAction(){
		//Không cần file loadDistrict thì khai báo thêm 2 dòng code bên dưới
		Zend_layout::resetMvcInstance();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->_request->isPost()){
			$provinceid=$this->_request->getParam("provinceid");
			//$province=new Default_Model_Province();
			//$currentProvince=$province->fetchRow("ProvinceId={$provinceid}");
			$district=new Default_Model_District();
			$listDistricts=$district->fetchAll("ProvinceId={$provinceid}")->toArray();
			$return=array();
			foreach ($listDistricts as $key => $value) {
				$temp['id']=$value['DistrictId'];
				$temp['name']=$value['DistrictName'];
				$return[]=$temp;
			}
			echo json_encode($return);die();
		}		
		
	}
	
	public function activeAction(){
		$key=$this->_request->getParam("key");
		if(strlen($key)){
			$member=new Default_Model_Member();
			$currentMember=$member->fetchRow("ActiveKey='{$key}'");
			if(count($currentMember)){
				$db=Zend_Registry::get('db');
				$db->query("update members set ActiveKey=null, Active=1 where MemberId={$currentMember['MemberId']}");
			}else{
				
			}
		}
	}
	
	public function loginAction() {
		//$this->view->Title = 'General Manager :: Download CSV All Members';
		//$this->_helper->layout ()->setLayout ( 'dosurvey' );
	    if ($this->_request->isPost()) {	
	        //1.Goi ket noi voi Zend Db
	        $db = Zend_Registry::get('db');
	        //$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
	        //2. Khoi tao Zend Autho
	        $auth = Zend_Auth::getInstance ();
	
	        //3. Khai bao bang va 2 cot se su dung so sanh trong qua trong login
	        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
	        $authAdapter->setTableName('members')
	                ->setIdentityColumn('Email')
	                ->setCredentialColumn('Password');
	
	        //4. Lay gia tri duoc gui qua tu FORM
	        $email = $this->_request->getParam('txtEmail');
	        $paswd = $this->_request->getParam('txtPassword');
	
	        //5. Dua vao so sanh voi du lieu khai bao o muc 3
	        $authAdapter->setIdentity($email);
	        $authAdapter->setCredential(md5($paswd));
	
	        //6. Kiem tra trang thai cua user neu Active = 1 moi duoc login
	        $select = $authAdapter->getDbSelect();
	        $select->where('Active = 1');
	
	        //7. Lay ket qua truy van
	        $result = $auth->authenticate($authAdapter);
	        $flag = false;
	        if ($result->isValid()) {
	            //8. Lay nhung du lieu can thiet trong bang members neu login thanh cong				
	            $data = $authAdapter->getResultRowObject(null, array('password'));
	
	            //9. Luu  nhung du lieu cua member vao session
	            $auth->getStorage()->write($data);
	            $flag = true;
                //var_dump($auth); die();
	        }
	        if ($flag == true) {
	            $this->_redirect('/user/my-account');
	        }
            else{
               // echo "<div class='form_row_login'><h4 style='color:red'>Bạn chưa đăng ký là thành viên hay bạn đã quên password rồi!</h4></div>";
               	$this->view->notice='Bạn chưa đăng ký hoặc chưa kích hoạt tài khoản để trở thành thành viên hay bạn đã quên password rồi!';
            }
	    }
	}

	public function logoutAction() {
		//Zend_layout::resetMvcInstance();
		//$this->_helper->viewRenderer->setNoRender(true);
	    $auth = Zend_Auth::getInstance();
		$infoUser = $auth->getIdentity();
		var_dump($infoUser);
		$currentUser=new Zend_Session_Namespace("Zend_Auth");
		var_dump($infoUser->Email);
	   // $auth->clearIdentity();
	}
	
	public function orderHistoryAction(){

	}
	
	public function commentAction(){
		
	}

	public function cartAction(){
		
	}
	
	public function directPaymentAction(){
		
	} 
	
	public function transferBankPaymentAction(){
		
	}
	
	public function wishlistAction(){
		
	}
	
	public function detailAction(){
		
	}
    
    public function myAccountAction(){
        $Province=new Default_Model_Province();
        $District = new Default_Model_District;
        //$User = new Default_Model_Member;
        $userinfo=Zend_Auth::getInstance()->getStorage()->read();              
        //var_dump($userinfo); die();
        //$user = $User->fetchRow("Email='haimydt@yahoo.com'");
        //$user1=$userinfo->Email;        
        //$user = $User->fetchRow("Email=$userinfo->Email");
         //var_dump($user); die();      
        //var_dump($user); die();            
        //var_dump($district); die();
        $district = $District->fetchRow("DistrictId=$userinfo->DistrictId");
        $province = $district[ProvinceId];
        //var_dump($province); die();
        $this->view->user=$userinfo;
        $this->view->district=$district;
        $this->view->provinceId = $province;
        $this->view->listDistricts=$District->fetchAll()->toArray();
        $this->view->listProvinces=$Province->fetchAll()->toArray();
    }  
    
    public function forgotPasswordAction(){
        
    }  
    
    public function checkoutAction(){
        $Province=new Default_Model_Province();
        $District = new Default_Model_District();
        $PaymentMethod = new Default_Model_PaymentMethod();
        $userinfo=Zend_Auth::getInstance()->getStorage()->read();
        $district = $District->fetchRow("DistrictId=$userinfo->DistrictId");
        $province = $district[ProvinceId];
        $this->view->user=$userinfo;
        $this->view->district=$district;
        $this->view->provinceId = $province;
        $this->view->listDistricts=$District->fetchAll()->toArray();
        $this->view->listProvinces=$Province->fetchAll()->toArray();
        $this->view->listPaymentMethods = $PaymentMethod->fetchAll()->toArray();
    }
    
    public function eventAction(){
        
    }
   
}









